# application/api/detection/mistake.py
from flask import Blueprint, jsonify, request
from application.services.detection.mistake import MistakeService
from application.utils.common import parse_id_list
from application.utils.res import json_fail, json_success, page_success

# 创建蓝图
bp = Blueprint("mistake", __name__, url_prefix="/mistake")


@bp.get("/list")
def get_mistake_list():
    """
    分页获取错误列表
    支持条件查询：pageNum, pageSize, productId 等条件
    """
    try:
        # 获取分页参数
        page_num = int(request.args.get("pageNum", 1))
        page_size = int(request.args.get("pageSize", 10))

        # 获取查询条件
        conditions = {
            "productId": request.args.get("productId"),
            "mistakeName": request.args.get("mistakeName"),
            "mistakeNo": request.args.get("mistakeNo"),
            "mistakeType": request.args.get("mistakeType"),
            # 可以根据实际需求添加更多查询条件
        }

        # 过滤空值条件
        filtered_conditions = {
            k: v for k, v in conditions.items() if v is not None and v != ""
        }

        # 调用服务获取数据
        mistake_list, total = MistakeService.get_mistake_list(
            page_num, page_size, filtered_conditions
        )

        return page_success(mistake_list, total)
    except Exception as e:
        return json_fail(f"查询失败: {str(e)}"), 500


@bp.post("")
def create_mistake():
    """
    创建错误记录
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        if not data:
            return json_fail("请求数据不能为空"), 400
            
        result = MistakeService.create_mistake(data)
        return json_success(result, "创建成功", 200)
    except Exception as e:
        return json_fail(f"创建失败: {str(e)}"), 500


@bp.put("")
def update_mistake():
    """
    更新错误记录
    :param mistake_id: 错误ID
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        if not data:
            return json_fail("请求数据不能为空"), 400
        
        mistake_id = data.get("mistakeId")
        if not mistake_id:
            return json_fail("错误ID不能为空"), 400
        
        # 调用服务层方法
        result = MistakeService.update_mistake(mistake_id, data)
        if result:
            return json_success(result, "更新成功")
        else:
            return json_fail("错误记录不存在"), 404
    except Exception as e:
        return json_fail(f"更新失败: {str(e)}"), 500



    
@bp.delete("/<string:mistake_ids>")
def batch_delete_mistake(mistake_ids):
    """
    删除绕组
    :param coil_id: 绕组ID
    """
    try:
        id_list = parse_id_list(mistake_ids)

        count = MistakeService.batch_delete_mistake(id_list)
      
        return json_success(count, "删除成功")
       
    except Exception as e:
        return json_fail(f"删除失败: {str(e)}"), 500
